import { timestampToTime } from "../../utils/util";
import { get, put, Domain } from "../../utils/request";
import { APIS } from "../../utils/api";
// pages/storemanage/index.js
Page({
  data: {
    currShop: {},
    actIdx: 0,
    date: 0,
    startDate: "-",
    endDate: "-",
    rangeStart: "2024-01-01",
    rangeEnd: "1990-01-01",
    vistorList: [],
    operating: {},
  },

  onLoad() {
    const currShop = wx.getStorageSync("currShop");
    const temp = new Date().getTime();
    const startDate = timestampToTime(temp);
    this.setData({
      currShop,
      startDate,
      endDate: startDate,
      rangeEnd: startDate,
    });
    this.getShopDetail(currShop.id);
  },

  // 保存店铺信息
  submitForm() {
    const { operating } = this.data;
    put(`${APIS.shop}/${operating.id}`, operating).then((res) => {
      wx.setStorageSync("currShop", res.data);
      if (res.code === 0) {
        wx.showToast({
          title: "保存成功",
          icon: "success",
          duration: 800,
        });
      }
    });
  },

  chooseImage(event) {
    const value = event.currentTarget.dataset.id;
    const that = this;
    wx.chooseImage({
      count: 1, // 默认选择一张图片
      sizeType: ["original", "compressed"], // 可以选择原图或压缩图
      sourceType: ["album", "camera"], // 可以选择来自相册或摄像头
      success(res) {
        // 成功选择图片后，获取文件路径
        // that.setData({
        //   imageSrc: res.tempFilePaths[0],
        // });
        // 上传至后台
        console.log('123123', value);
        wx.uploadFile({
          url: `${Domain}${APIS.upload}`,
          filePath: res.tempFilePaths[0],
          name: "file",
          success(res) {
            console.log(res);
            try {
              const obj = JSON.parse(res.data);
              const operatingNew = that.data.operating;
              operatingNew[value] = obj.data.file
              console.log(operatingNew);
              that.setData({
                operating: {
                  ...operatingNew
                },
              });
            } catch(e) {
              throw e;
            }
          },
          fail(err) {
            console.error(err);
          }
        });
      },
      fail(err) {
        console.error(err);
      },
    });
  },

  handleShopChange(e) {
    let currShop = e.detail;
    this.setData({
      currShop,
    });
    if (this.data.actIdx === 1) {
      this.getVisitor();
    }
  },

  handelTab(e) {
    let actIdx = e.target.dataset.key;
    console.log(actIdx);
    if (actIdx === this.data.actIdx) {
      return;
    }
    this.setData({
      actIdx,
    });
    if (actIdx === 1) {
      this.getVisitor();
    }
  },
  handelDateTab(e) {
    let date = e.target.dataset.key;
    if (date === this.data.date) {
      return;
    }
    this.setTime(date === 0 ? "today" : "yestoday");
    this.setData({
      date,
    });
    this.getVisitor();
  },

  bindStartChange(e) {
    let date = e.detail.value;
    let endDate =
      new Date(date) < new Date(this.data.endDate) ? this.data.endDate : date;
    this.setData({
      startDate: date,
      endDate,
      date: -1,
    });
    this.getVisitor();
  },
  bindEndChange(e) {
    this.setData({
      endDate: e.detail.value,
      date: -1,
    });
    this.getVisitor();
  },

  setTime(mode) {
    let startDate = "";
    let endDate = "";
    let t = new Date(
      Date.now() - Number(mode === "yestoday") * 24 * 3600 * 1000
    );
    startDate = endDate = `${t.getFullYear()}-${String(
      t.getMonth() + 1
    ).padStart(2, "0")}-${String(t.getDate()).padStart(2, "0")}`;
    this.setData({
      startDate,
      endDate,
    });
  },

  // 获取店铺detail
  getShopDetail(id) {
    get(`${APIS.shop}/${id}`).then((res) => {
      this.setData({
        operating: res.data,
      });
    });
  },
  getVisitor() {
    let { currShop, startDate, endDate } = this.data;
    get(APIS.vip + "/vistor", {
      shop: currShop.id,
      start: startDate,
      end: endDate,
    }).then((res) => {
      this.setData({
        vistorList: res.data,
      });
    });
  },
  handleUser(e) {
    let user = e.currentTarget.dataset.user;
    wx.navigateTo({
      url: "/pages/visitor/index?uid=" + user.id,
    });
  },
});
